package com.ruoyi.web.controller.obs.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.obs.services.ObsClient;
import com.obs.services.model.PutObjectResult;
import com.ruoyi.common.config.RuoYiConfig;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.file.FileUploadUtils;
import com.ruoyi.web.controller.obs.config.ObsProperties;
import com.ruoyi.modules.domain.Credit;
import com.ruoyi.modules.service.CreditService;
import com.ruoyi.web.controller.obs.util.Xml2Json;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.dom4j.DocumentException;
import org.jodconverter.DocumentConverter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.*;

/**
 * 对象存储 obs
 */
@RestController
@RequestMapping("/obs")
public class FileController extends BaseController {

    @Value("${obs.url}")
    private String obsUrl;

    @Autowired
    private DocumentConverter converter;

    @Autowired
    private CreditService creditService;

    @Autowired
    private ObsProperties obsProperties;

    private static Logger LOGGER = LoggerFactory.getLogger(FileController.class);

    /**
     * 上传word文件
     * @param file 文件
     * @param creditId 贷款编号
     * @param request
     * @return
     * @throws Exception
     */
    @PostMapping
    public AjaxResult FileUpload(@RequestParam("file") MultipartFile file, @RequestParam("creditId") Long creditId, HttpServletRequest request) throws Exception {

        AjaxResult ajax = AjaxResult.success();

        if (!file.isEmpty()) {

            InputStream in = null;
            ObsClient obsClient = null;

            //获取文件名称，作为上传文件名参数
            String objectKey = file.getOriginalFilename();
            //获取流对象
            in = file.getInputStream();
            // 创建ObsClient实例
            obsClient = new ObsClient(obsProperties.getAk(), obsProperties.getSk(), obsProperties.getEndPoint());
            // 使用访问OBS
            PutObjectResult putObjectResult = obsClient.putObject("tlgenhuawei", objectKey, in);
            //将图片信息封装起来，方便前端回显调用
            String url = putObjectResult.getObjectUrl();

            System.out.println("华为obs上传成功预览的url为: " + url);

            ajax.put("name", objectKey);
            ajax.put("url", url);

            Credit credit = creditService.selectCreditById(creditId);

            String uploadWordName = file.getOriginalFilename();

            // multipartFile转java.io.File
            File toFile = null;
            if(file.equals("")||file.getSize()<=0){
                file = null;
            }else {
                InputStream ins = null;
                ins = file.getInputStream();
                toFile = new File(file.getOriginalFilename());
                inputStreamToFile(ins, toFile);
                ins.close();
            }

            System.out.println(toFile);

            // 文件转化
            converter.convert(toFile).to(new File("E:/new.pdf")).execute();
            System.out.println("word文件转换成pdf文件成功!");

            // 程序结束时删除临时文件
            deleteFile(toFile);

            String filePath = "E:/new.pdf";
            // 将java.io.File转为MultipartFile
            File newFile = new File(filePath);
            FileInputStream inputStream = new FileInputStream(newFile);
            MultipartFile multipartFile = new MockMultipartFile("file", newFile.getName(), "text/plain", IOUtils.toByteArray(inputStream));

            System.out.println(multipartFile);

            String uploadWordPath = FileUploadUtils.upload(RuoYiConfig.getUploadWordFile(), multipartFile);
            System.out.println(uploadWordPath);

            if (creditService.updateCreditUploadWord(creditId, uploadWordPath, uploadWordName)) {
                ajax.put("uploadWordPath", uploadWordPath);
                ajax.put("message", "上传成功");
                ajax.put("fileName", file.getOriginalFilename());
                ajax.put("path", url);
                credit.setUploadWordPath(uploadWordPath);
                credit.setUploadWordName(file.getOriginalFilename());
                creditService.updateCredit(credit);
                return ajax;
            }

            in.close();
            obsClient.close();
        }

        return AjaxResult.error("上传word文件失败!");

    }

    /**
     * InputStream 转 File
     * @param ins
     * @param file
     */
    public static void inputStreamToFile(InputStream ins, File file) {
        try {
            OutputStream os = new FileOutputStream(file);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
            os.close();
            ins.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    // 删除临时文件
    private void deleteFile(File... files) {
        for (File file : files) {
            if (file.exists()) {
                file.delete();

            }

        }
    }


    @GetMapping("/all")
    public TableDataInfo getAllObs() throws IOException, DocumentException {

        HttpGet httpGet = new HttpGet(obsUrl);
        httpGet.setHeader("Content-Type", "application/x-www-form-urlencoded");

        System.out.println("调用URL: " + httpGet.getURI());

        CloseableHttpClient httpClient = HttpClients.createDefault();
        HttpResponse response = httpClient.execute(httpGet);
        HttpEntity entity = response.getEntity();

        System.out.println("返回状态码：" + response.getStatusLine());

        BufferedReader reader = new BufferedReader(new InputStreamReader(entity.getContent(), "UTF-8"));
        String line = null;
        StringBuffer buffer = new StringBuffer();

        while ((line = reader.readLine()) != null) {
            buffer.append(line);
        }

        JSONObject json = Xml2Json.xml2Json(buffer.toString());
        System.out.println(json);

        // 解析 com.alibaba.fastjson.JSONObject
        JSONObject listBucketResult = json.getJSONObject("ListBucketResult");
        JSONArray contents = listBucketResult.getJSONArray("Contents");

        // 分页返回
        startPage();
        getDataTable(contents);

        reader.close();
        httpClient.close();

        System.out.println(getDataTable(contents));

        return getDataTable(contents);

    }


}
